package com.example.openharmony.controller;

import com.example.openharmony.entity.User;
import com.example.openharmony.entity.VerificationCode;
import com.example.openharmony.repository.UserRepository;
import com.example.openharmony.repository.VerificationCodeRepository;
import com.example.openharmony.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.time.LocalDateTime;
import java.util.*;

/**
 * 认证控制器
 * 处理用户登录、注册、验证码等相关接口
 */
@RestController
@RequestMapping("/api/auth")
public class AuthController {
    
    @Autowired
    private UserService userService;
    
    @Autowired
    private UserRepository userRepository;
    
    @Autowired
    private VerificationCodeRepository verificationCodeRepository;
    
    /**
     * 发送验证码接口
     * @param phone 手机号
     * @return 发送结果
     */
    @PostMapping("/send-code")
    public Map<String, Object> sendVerificationCode(@RequestParam String phone) {
        // 生成6位随机验证码
        String code = String.format("%06d", new Random().nextInt(999999));
        
        // 保存验证码到数据库
        VerificationCode verificationCode = new VerificationCode();
        verificationCode.setPhone(phone);
        verificationCode.setCode(code);
        verificationCode.setExpiresAt(LocalDateTime.now().plusMinutes(5)); // 5分钟过期
        
        verificationCodeRepository.save(verificationCode);
        
        // TODO: 实际项目中应调用短信服务发送验证码
        System.out.println("验证码: " + code);
        
        return Map.of("success", true, "message", "验证码已发送");
    }
    
    /**
     * 验证码登录接口
     * @param phone 手机号
     * @param code 验证码
     * @return 登录结果
     */
    @PostMapping("/login-with-code")
    public Map<String, Object> loginWithCode(@RequestParam String phone, @RequestParam String code) {
        // 查找有效的验证码
        Optional<VerificationCode> verificationCodeOpt = verificationCodeRepository
                .findByPhoneAndExpiresAtAfter(phone, LocalDateTime.now());
        
        if (verificationCodeOpt.isPresent() && verificationCodeOpt.get().getCode().equals(code)) {
            // 验证码正确，查找或创建用户
            Optional<User> userOpt = userService.findByPhone(phone);
            User user;
            
            if (userOpt.isPresent()) {
                user = userOpt.get();
            } else {
                // 创建新用户
                user = new User();
                user.setPhone(phone);
                user.setUsername("user_" + System.currentTimeMillis()); // 临时用户名
                user.setPassword(""); // 验证码登录不需要密码
                user = userService.save(user);
            }
            
            return Map.of("success", true, "message", "登录成功", "user", user);
        } else {
            return Map.of("success", false, "message", "验证码错误或已过期");
        }
    }
    
    /**
     * 密码登录接口
     * @param identifier 用户名/手机号
     * @param password 密码
     * @return 登录结果
     */
    @PostMapping("/login-with-password")
    public Map<String, Object> loginWithPassword(@RequestParam String identifier, @RequestParam String password) {
        // 根据用户名或手机号查找用户
        Optional<User> userOpt = userService.findByUsername(identifier);
        if (!userOpt.isPresent()) {
            userOpt = userService.findByPhone(identifier);
        }
        
        if (userOpt.isPresent() && userOpt.get().getPassword().equals(password)) {
            return Map.of("success", true, "message", "登录成功", "user", userOpt.get());
        } else {
            return Map.of("success", false, "message", "用户名或密码错误");
        }
    }
}